package org.lanzier.common.service.impl;

import java.util.Map;

import org.lanzier.common.exception.LanzierException;
import org.lanzier.common.form.RequestDataForm;
import org.lanzier.common.form.ResponseDataForm;
import org.lanzier.common.sqlparse.SqlResultForm;
import org.lanzier.common.utils.MapUtils;
import org.lanzier.common.utils.XmlUtils;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author lansb ajax Service
 */
@Service("ajaxService")
public class AjaxService extends AbstractService {
	public ResponseDataForm service(RequestDataForm requestDataForm) throws Exception {
		// 实现如下:
		ResponseDataForm rdf = new ResponseDataForm(); 
		Map<String, Object> urlSqlMap = requestDataForm.getUrlSqlMap();
		Map<String, String> simpleRequestMap = requestDataForm.getSimpleRequestMap();
		String execSql = MapUtils.getString(urlSqlMap, "EXEC_SQL");
		logger.debug("\n\r\t 待解析的xml：" + execSql);
		if ("".equals(execSql)) {
			throw new LanzierException("exec sql is null");
		}
		NodeList sqlNodes = XmlUtils.getNoteListByString(execSql);
		
		Element element = null;
		for (int i = 0; i < sqlNodes.getLength(); i++) {
			Node child = sqlNodes.item(i);
			if (child.getNodeType() != Node.ELEMENT_NODE)
				continue;
			element = (Element) child;
			SqlResultForm srf = sqlParse.parseNode(element, simpleRequestMap);
			Object ajaxObject = null;
			String resultType = element.getAttribute("resultType");
			if("list".equals(resultType)) {
				ajaxObject = jdbcDao.queryForList(srf.getParsedSql(), srf.getValueList().toArray());
			} else if("map".equals(resultType)) {
				ajaxObject = jdbcDao.queryForMap(srf.getParsedSql(), srf.getValueList().toArray());
			} else {
				ajaxObject = jdbcDao.queryForString(srf.getParsedSql(), srf.getValueList().toArray());
			}
			rdf.setAjaxObject(ajaxObject);
		}
		return rdf;
	}
}
